package com.polaris.live.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ColorUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.HonorUserProfileAdapter
import com.polaris.live.adapter.UserProfilePhotoAdapter
import com.polaris.live.common.R.color
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.WidgetUserProfileBaseBinding
import com.polaris.live.dialog.HonorBannerDialog
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.DecorationUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.viewscope.autoDisposeScope
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libpag.PAGFile

/**
 * 个人资料卡片公共视图
 * @author Created by 天晴 on 2024/3/2 15:36
 * @since 1.0.0
 **/
class UserProfileBaseView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

    private val mBinding = WidgetUserProfileBaseBinding.inflate(LayoutInflater.from(context), this)

    private val mAdapter by lazy { UserProfilePhotoAdapter() }

    private val mHonorAdapter by lazy { HonorUserProfileAdapter() }

    /**
     * 是否是聊天室主播
     * goneCall  隐藏拨打电话
     */
    fun initView(
        infoOtherResp: InfoOtherResp,
        mPage: Int,
        goneCall: Boolean,
        onStartCallClickListener: () -> Unit,
        onImageClickListener: (list: ArrayList<String>, view: View, position: Int) -> Unit,
        onTopListener: (top: Int) -> Unit,
        onAvatarListener: () -> Unit,
    ) {

        mBinding.apply {
            if (!infoOtherResp.medals.isNullOrEmpty()) {
                honorRecycler.apply {
                    visibility = View.VISIBLE
                    adapter = mHonorAdapter
                    layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                }
                if (infoOtherResp.userId == UserManager.getUserId()) {
                    mHonorAdapter.setList(infoOtherResp.medals)
                } else {
                    val newList = infoOtherResp.medals.filter { it.createTime != null }
                    mHonorAdapter.setList(newList)
                }
            } else {
                honorRecycler.visibility = View.GONE
            }
            idView.setId(infoOtherResp)
            userAvatar.setImageUrlMiddle(infoOtherResp.avatar, infoOtherResp.userId)
            avFv.setFrameImageCompleted { parentWidth, parentHeight, bottomHeight ->
                setUi(infoOtherResp, parentWidth, parentHeight, onTopListener, bottomHeight)
            }
            avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(infoOtherResp.decoration?.avatarFrame))
            userName.text = infoOtherResp.nickname
            userName.setNicknameColor(
                infoOtherResp.decoration?.nicknameColor,
                color.color_202028
            )

            saSex.setSexAndAge(infoOtherResp.sex, infoOtherResp.birthday)

            if (infoOtherResp.flag.official == 1L) {
                mBinding.ivOfficial.visibility = View.VISIBLE
            } else {
                mBinding.ivOfficial.visibility = View.GONE
            }

            country.setCountry(infoOtherResp.profile.country)
            language.setLanguage(infoOtherResp.profile.secondLanguage)
            mBinding.vipView.setVipLevel(infoOtherResp.profile.vipLevel)
            if (CommonUtils.isMan(infoOtherResp.sex)) {
                widgetLevel1.setRichsLevel(infoOtherResp.account.richs)
                widgetLevel2.setCharmsLevel(infoOtherResp.account.charms)
            } else {
                widgetLevel1.setCharmsLevel(infoOtherResp.account.charms)
                widgetLevel2.setRichsLevel(infoOtherResp.account.richs)
            }

            if (isShowCall(infoOtherResp) || goneCall) {
                goCall.visibility = View.GONE
                freeMatch.visibility = View.GONE
            } else {
//                if (infoOtherResp.call?.actualPrice == 0L) {
//                    mBinding.goCall.visibility = View.GONE
//                    mBinding.freeMatch.visibility = View.VISIBLE
//                } else {
//                    mBinding.freeMatch.visibility = View.GONE
//                    mBinding.callCoin.text = "${infoOtherResp.call?.actualPrice}"
//                    mBinding.goCall.visibility = View.VISIBLE
//                    ivPlay.apply {
//                        path = PagConst.USER_PROFILE_CALL_PAG
//                        setRepeatCount(-1)
//                        play()
//                    }
//                }
            }
            mBinding.wdigetFlag.setLabel(infoOtherResp.flag.label)

            if (CollectionUtils.isEmpty(infoOtherResp.photos)) {
                mBinding.relPhotos.visibility = View.GONE
            } else {
                //展示相册
                recycler.apply {
                    adapter = mAdapter
                    layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                }
                mAdapter.setList(infoOtherResp.photos)
                if (infoOtherResp.photos.size > 4) {
                    photosNext.visibility = View.VISIBLE
                }
            }
            goCall.setOnSingleClickListener {
                onStartCallClickListener.invoke()
            }

            userAvatar.setOnSingleClickListener {
                if (PartyUserStateUtil.inTheGame) {
                    ToastGravity.showGravity(string.party_paly_game_click_avater)
                    return@setOnSingleClickListener
                }
                if (PartyUserStateUtil.inTheGameSeat) {
                    ToastGravity.showGravity(string.party_paly_seat_click_avater)
                    return@setOnSingleClickListener
                }
                if (LiveStateManager.isLiving() || LiveStateManager.isCalling()) {
                    return@setOnSingleClickListener
                }
                onAvatarListener.invoke()
            }
            freeMatch.setOnSingleClickListener {
                goCall.performClick()
            }
        }
        mAdapter.setOnItemClickListener { _, view, position ->
            onImageClickListener.invoke(
                ArrayList(mAdapter.data.map { ImageUtils.imgPath(it.url) }),
                view,
                position
            )
        }
        mHonorAdapter.setOnItemClickListener { _, _, position ->
            XPopup.Builder(context)
                .shadowBgColor(ColorUtils.getColor(R.color.color_000_85))
                .isDestroyOnDismiss(true)
                .asCustom(HonorBannerDialog(context, mHonorAdapter.data, position))
                .show()
        }
    }

    /**
     * 計算头像和背景位置调整
     */
    private fun setUi(
        infoOtherResp: InfoOtherResp,
        parentWidth: Int,
        parentHeight: Int,
        onTopListener: (top: Int) -> Unit,
        bottomHeight: Int,
    ) {
        //这里的宽高计算都删掉的原因是，ui那边定死范围，客户端直接写死就行，ui后面就按照这个尺寸来出图了
        if (infoOtherResp.decoration?.avatarFrame?.isNotEmpty() == true) {
            val layoutParams = mBinding.avFv.layoutParams as MarginLayoutParams
            layoutParams.topMargin = -(6).autoDp
            mBinding.avFv.layoutParams = layoutParams
        }
        mBinding.apply {
            val data =
                DecorationUtils.getDecorationProfileBackground(infoOtherResp.decoration?.profileBackground)
            data?.run {
                if (pag == 1) {
                    val path = if (url.endsWith(".png")) {
                        url.substring(0, url.length - 4) + ".pag"
                    } else {
                        url
                    }
                    backPag.visibility = View.GONE
                    backImg.visibility = View.VISIBLE
                    autoDisposeScope.launch {
                        DownLoadFileUtil.getPagPath(path)?.let { path ->
                            withContext(CoroutineScopeManager.mainDispatcher) {
                                backPag.apply {
                                    backPag.visibility = VISIBLE
                                    setRepeatCount(-1)
                                    composition = PAGFile.Load(path)
                                    play()
                                    delay(200)
                                    backImg.visibility = GONE
                                }
                            }
                        }
                    }

                } else {
                    backPag.visibility = View.GONE
                    backImg.visibility = View.VISIBLE
                    Glide.with(context)
                        .load(ImageUtils.imgPath(url))
                        .placeholder(R.drawable.img_bg)
                        .into(object : CustomViewTarget<View, Drawable>(backImg) {
                            override fun onResourceReady(
                                resource: Drawable,
                                transition: Transition<in Drawable>?,
                            ) {
                                backImg.setImageDrawable(resource)
                            }

                            override fun onLoadFailed(errorDrawable: Drawable?) {
                            }

                            override fun onResourceCleared(placeholder: Drawable?) {
                            }
                        })
                }
            }
        }
    }

    fun isShowCall(infoOtherResp: InfoOtherResp): Boolean {
        return (infoOtherResp.userId == UserManager.getUser().userId
                || LiveStateManager.isCalling()
                || LiveStateManager.getState() != LiveConst.State.NONE
                || (infoOtherResp.live?.living == true && infoOtherResp.live?.liveType == LiveConst.Type.ONLY_LIVE))

    }
}